package com.qf.controller;

import com.qf.captcha.CaptchaCodeManager;
import com.qf.pojo.DtsAdmin;
import com.qf.service.PermissionService;
import com.qf.service.RoleService;
import com.qf.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

//登录
@RestController
@CrossOrigin
@RequestMapping("/admin/auth")
@Slf4j
public class AdminAuthController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;


    /**
     * 验证码
     * @return
     *
     * {
     *     "errno":0,
     *  	"data":	{
     *         "img":"/9j/4AAQSkZJRlZ/2Q==",
     *         "uuid":"b5ca22d8b9e14a88b2851da906d19e4f"
     *     },
     *     "errmsg":"成功"
     * }
     */
    @GetMapping("/captchaImage")
    public Object captchaImage() throws IOException {

        //验证码图片
        String code = VerifyCodeUtils.generateVerifyCode(4);


        //uuid
        String uuid = UUID.randomUUID(true).toString();

        //验证码图片
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(111, 36, outputStream, code);

        //验证码保存在session中  uuid 就是kay  //默认三分钟
        CaptchaCodeManager.addToCache(uuid, code,null);

        //取出验证码
        //String cachedCaptcha = CaptchaCodeManager.getCachedCaptcha(uuid);


        Map<String, Object> result = new HashMap<>();
        result.put("img", Base64.encode(outputStream.toByteArray()));
        result.put("uuid", uuid);

        return  ResponseUtil.ok(result);
    }


    //登录
    @PostMapping("/login")
    public Object Login(@RequestBody String body){

        String code = JacksonUtil.parseString(body, "code");
        String password = JacksonUtil.parseString(body, "password");
        String username = JacksonUtil.parseString(body, "username");
        String uuid = JacksonUtil.parseString(body, "uuid");

        //验证码是否正确
        /*String cachedCaptcha = CaptchaCodeManager.getCachedCaptcha(uuid);
        if (StringUtils.isEmpty(cachedCaptcha)){
            log.error("登录发生错误：{}",AdminResponseCode.AUTH_CAPTCHA_EXPIRED.desc());
            //验证码失效（过期）
            return AdminResponseUtil.fail(AdminResponseCode.AUTH_CAPTCHA_EXPIRED);
        }
        if (!cachedCaptcha.equalsIgnoreCase(code)){
            log.error("登录发生错误：{}",AdminResponseCode.AUTH_CAPTCHA_ERROR.desc());
            //验证码错误（过期）
            return AdminResponseUtil.fail(AdminResponseCode.AUTH_CAPTCHA_ERROR);
        }
*/
        //开始校验用户名 密码是否正确   登录

        Md5Hash md5Hash = new Md5Hash(password, username, 1024);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(username, md5Hash.toString()));
        } catch (AuthenticationException e) {

            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_ACCOUNT_OR_PASSWORD);
        }
        //登录成功  sessionId
        Session session = subject.getSession();
        return  ResponseUtil.ok(session.getId());

    }


    //登录后获取用户名，角色 权限
    @GetMapping("/info")
    public Object info(){

        Subject subject = SecurityUtils.getSubject();
        DtsAdmin principal = (DtsAdmin) subject.getPrincipal();

        //获取用户名
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("name", principal.getUsername());
        hashMap.put("avatar", principal.getAvatar());

        //获取当前用户角色
        Set<String> role = roleService.queryByRoleIds(principal.getRoleIds());

        //获取当前用户的权限
        Set<String> permission = permissionService.queryByRoleIds(principal.getRoleIds());

        //写入hashmap
        hashMap.put("roles",role);
        hashMap.put("perms", permission);

        return ResponseUtil.ok(hashMap);
    }


   /* public static void main(String[] args) {
        Md5Hash md5Hash = new Md5Hash("123456", "qianfeng", 1024);
        System.out.println(md5Hash);
    }*/
}
